package com.yonyou.ucf.mdf.app.isvdxq.other.service;

import com.yonyou.iuap.context.InvocationInfoProxy;
import com.yonyou.iuap.tenant.sdk.TenantCenter;
import com.yonyou.iuap.tenant.sdk.UserCenter;
import com.yonyou.ucf.mdf.app.isvdxq.other.model.AccessTokenResponse;
import com.yonyou.ucf.mdf.app.isvdxq.other.model.DcUrlResult;
import com.yonyou.ucf.mdf.app.isvdxq.utils.MyTool;
import com.yonyou.ucf.mdf.app.isvdxq.yonyisv.service.OpenApiRequestService;
import com.yonyoucloud.iuap.ucf.mdd.starter.ucg.openapi.OpenApiProperties;
import com.yonyoucloud.iuap.ucf.mdd.starter.ucg.openapi.module.auth.isv.ISVAuthProvider;
import com.yonyoucloud.iuap.ucf.mdd.starter.ucg.openapi.module.auth.tenant.TenantAuthProvider;
import com.yonyoucloud.iuap.ucf.mdd.starter.ucg.openapi.module.common.OpenApiAccessToken;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

@Service
public class MyTokenService {
    private static final Logger logger = LoggerFactory.getLogger(MyTokenService.class);
    @Autowired
    DcService dcService;
    @Autowired
    OpenApiRequestService openApiRequestService;

    /**
     * openApiProperties.getTenantId()
     */
    @Autowired
    private OpenApiProperties openApiProperties;
    @Autowired
    private TenantAuthProvider tenantAuthProvider;
    @Autowired
    private ISVAuthProvider isvAuthProvider;

    /**
     * 获取 TenantId
     * AppContext.getTenantId() 上下文数据
     * openApiProperties.getTenantId() 主账户数据
     * InvocationInfoProxy.getToken()
     * api 访问无上下文
     * String tenantid = InvocationInfoProxy.getTenantid();
     * todo 根据 yht_access_token 获取用户信息
     * @return
     */
    public String getTenantId() {
        String tenantId = InvocationInfoProxy.getTenantid();
//        if (StringUtils.isEmpty(tenantId)) {
//            tenantId = AppContext.getTenantId();
//        }
        return tenantId;
    }


    /**
     * 获取友互通用户ID
     *
     * @return
     */
    public String getYhtUserid() {
//        AppContext.getAppConfig().getProperty("");
//        return "0aa3cf76-2826-4acb-9f96-c6f3e6678c95";
        String userId = InvocationInfoProxy.getUserid();
//        if (StringUtils.isEmpty(userId)){
//            userId = AppContext.getUserId();
//        }
        return userId;
    }

    /**
     * 获取租户信息
     *
     * @param tenantId
     * @return
     */
    public String getTenantById(String tenantId) {
        String tenantInfo = TenantCenter.getTenantById(tenantId);
        return tenantInfo;
//        Map<String,Object> res = new HashMap<>();
//        Map<String,Object> tenant = new HashMap<>();
//        tenant.put("tenantId", DxqConfig.tenantId);
//        tenant.put("tenantName", DxqConfig.tenantId);
//        res.put("tenant", tenant);
//
//        String tenantInfo = JSONObject.toJSONString(res);
//        return tenantInfo;
    }

    /**
     * 上下文获取用户信息
     * @return
     * @throws IOException
     */
    public Map<String, Object> getUserInfoByYhtToken() throws IOException {
        Map<String, Object> result = new HashMap<>();
        // 平台应用openapi 租户tenantId=wk9uhe4k 管理账户
        String yhtUserId = getYhtUserid();
        String tenantId = getTenantId();
        String loginToken = "";
        String tenantId1 = openApiProperties.getTenantId();
//        LoginUser userInfo = AppContext.getCurrentUser();
//        if (userInfo != null) {
//            tenantId = userInfo.getYhtTenantId();
//            yhtUserId = userInfo.getYhtUserId();
//            loginToken = userInfo.getYhtAccessToken();
//        }
        result.put("yhtUserId", yhtUserId);
        result.put("tenantId", tenantId);
        result.put("loginToken", loginToken);
        return result;
    }

    /**
     * 指定租户应用 获取getAccessToken
     * @param tenantId
     * @param appKey
     * @param appSecret
     * @return
     * @throws IOException
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     */
    public AccessTokenResponse getAccessTokenYonyou(String tenantId, String appKey, String appSecret) throws IOException, InvalidKeyException, NoSuchAlgorithmException {
        AccessTokenResponse accessTokenResponse = openApiRequestService.requestForAccessTokenV2(appKey, tenantId, appSecret);
        String accessToken = accessTokenResponse.getAccessToken();
        return accessTokenResponse;
    }

    /**
     * getAccessToken
     *
     * @param tenantId
     * @return
     */
    @SneakyThrows
    public AccessTokenResponse getAccessToken3(String tenantId) {
        AccessTokenResponse res = new AccessTokenResponse();
        res = getAccessToken(tenantId);
        return res;
    }


    /**
     * 根据套件key+租户获取token
     *
     * @param tenantId
     */
    public AccessTokenResponse getAccessToken(String tenantId) {
//        "b8zuak25"
//        String accessToken = openApiAuthProvider.buildAuthToken(tenantId).getAccessToken();
//        TokenResult tokenResult = commonAuthApi.generateToken(tenantId, CurrentUserUtil.getUserId());

        AccessTokenResponse res = new AccessTokenResponse();
        OpenApiAccessToken resToken = new OpenApiAccessToken();
        // String tempTenantId = openApiProperties.getTenantId();
        if (StringUtils.isNotBlank(tenantId)){
            resToken = isvAuthProvider.buildISVAuthToken(tenantId);
        } else {
            resToken = tenantAuthProvider.buildTenantAuthToken();
        }
        res.setAccessToken(resToken.getAccessToken());
        res.setAccessToken(URLEncoder.encode(resToken.getAccessToken()));
        res.setExpire((resToken.getExpiredAt() - System.currentTimeMillis()) / 1000);

        return res;
    }

    /**
     * 本地私有token
     *
     * @param tenantId
     * @return
     */
    public OpenApiAccessToken getAccessTokenLocal(String tenantId) {
        OpenApiAccessToken resToken = new OpenApiAccessToken();
        resToken.setAccessToken(MyTool.GenerateDxqToken(tenantId));
        resToken.setExpiredAt(MyTool.timeGen(60 * 60));
        return resToken;
    }

    /**
     * 获取数据中心地址
     *
     * @param tenantId
     * @return
     * @throws IOException
     */
    public DcUrlResult getGateway(String tenantId) throws IOException {
        DcUrlResult result = dcService.getGateway(tenantId);
        return result;
    }

    /**
     * 用友在线平台放行
     * isYhtAccessTokenValid
     *
     * @param yht_access_token
     * @return
     */
    public boolean isYhtAccessTokenValid(String yht_access_token) {
        boolean flagCheck = UserCenter.isAccessTokenValid(yht_access_token);
        if (flagCheck) {
            return true;
        }
        return false;
    }

    /**
     * 用友权限token放行
     *
     * @param tenantId_Now
     * @param access_token
     * @return
     */
    public boolean isAccessToken(String tenantId_Now, String access_token) {
        AccessTokenResponse resToken = null;
        try {
            resToken = this.getAccessToken3(tenantId_Now);
        } catch (Exception ex) {
            System.out.println("[Token权限获取失败]" + ex.getMessage());
        } finally {
            if (resToken != null && resToken.getAccessToken().equals(access_token)) {
                return true;
            }
            return false;
        }
    }

//    public Properties getAppConfig() {
//        return AppContext.getAppConfig();
//    }

    @Autowired
    private Environment environment;
    public String getProperty(String key) {
        return getProperty(key, null);
    }

    public String getProperty(String key, String o) {
        if(o==null) {
            return environment.getProperty(key);
        }else{
            return environment.getProperty(key, o);
        }
    }

}
